/**
 * 我是约定入口文件
 */
import { isLogin } from '@/services';
import { requestConfig } from '@vh-admin/pro-services';
import global from '@/utils/globalUtils';
import { setUserLocalStorage, getUserTokenLocalStorage } from '@/utils/localStorageModel';
import { history, matchRoutes } from '@umijs/max';
import { ConfigProvider } from 'antd';
import React from 'react';
import theme from '../config/theme';

//比如用于在外面包一个 Provider， 解决弹窗的错误信息
export function rootContainer(container: any) {
  ConfigProvider.config({
    // 5.13.0+
    holderRender: (children) => <ConfigProvider theme={theme}>{children}</ConfigProvider>,
  });

  return React.createElement(ConfigProvider, null, container);
}

export function onRouteChange({ clientRoutes, location }: any) {
  const route = matchRoutes(clientRoutes, location.pathname)?.pop()?.route;
  if (!route) {
    history.push(`/404`);
  }
}

// 约定一个地方生产和消费初始化数据。
export async function getInitialState() {
  global.log('启动应用进入页面');

  if (history.location.pathname !== '/login' && history.location.pathname !== '/404') {
    if (getUserTokenLocalStorage()) {
      try {
        // 确认用户登陆权限、更新用户最新信息
        const res = await isLogin();
        setUserLocalStorage(res.data);
      } catch (error) {}
    } else {
      history.push('/login');
    }
  }
  // return { name: 'dasad' };
}

/**
 * 公用请求拦截器
 */
export const request = requestConfig;
